const questionService = require('../../../../services/question');

Page({
  data: {
    currentTab: 0,
    tabs: ['全部试题', '单选题', '多选题', '填空题', '解答题'],
    subjects: ['全部', '语文', '数学', '英语'],
    currentSubject: '全部',
    searchKeyword: '',
    questionList: [],
    totalCount: 0,
    pageSize: 10,
    currentPage: 1,
    isLoading: false,
    showFilterPopup: false,
    types: ['单选题', '多选题', '填空题', '解答题'],
    difficulties: ['简单', '中等', '困难'],
    selectedSubject: '',
    selectedType: '',
    selectedDifficulty: ''
  },

  onLoad: function() {
    this.loadQuestionData();
    // 添加页面加载动画效果
    wx.showNavigationBarLoading();
    setTimeout(() => {
      wx.hideNavigationBarLoading();
    }, 700);
  },

  // 返回上一页
  onBackClick: function() {
    this.showButtonFeedback();
    console.log('返回上一页');
    
    try {
      wx.navigateBack({
        delta: 1,
        fail: (err) => {
          console.error('返回失败:', err);
          // 如果返回失败，尝试重新导航到教师端首页
          wx.redirectTo({
            url: '/pages/teacher/home/home',
            fail: (redirectErr) => {
              console.error('重定向回教师端首页失败:', redirectErr);
              wx.showToast({
                title: '返回失败',
                icon: 'none'
              });
            }
          });
        }
      });
    } catch (error) {
      console.error('返回操作异常:', error);
    }
  },
  
  // 按钮点击反馈
  showButtonFeedback: function() {
    wx.vibrateShort({
      type: 'medium'
    });
  },

  // 切换选项卡
  switchTab: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index,
      currentPage: 1,
      selectedType: index === 0 ? '' : this.data.tabs[index]
    });
    this.loadQuestionData();
  },

  // 选择学科筛选
  selectSubject: function(e) {
    const subject = e.currentTarget.dataset.subject;
    this.setData({
      currentSubject: subject,
      currentPage: 1,
      showFilterPopup: false,
      selectedSubject: subject
    });
    this.loadQuestionData();
  },

  // 搜索试题
  searchQuestion: function(e) {
    this.setData({
      searchKeyword: e.detail.value,
      currentPage: 1
    });
    this.loadQuestionData();
  },

  // 显示筛选弹窗
  showFilter: function() {
    this.setData({
      showFilterPopup: true
    });
  },

  // 关闭筛选弹窗
  closeFilter: function() {
    this.setData({
      showFilterPopup: false
    });
  },

  // 选择题型
  selectType: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      selectedType: type
    });
  },

  // 选择难度
  selectDifficulty: function(e) {
    const difficulty = e.currentTarget.dataset.difficulty;
    this.setData({
      selectedDifficulty: difficulty
    });
  },

  // 重置筛选
  resetFilter: function() {
    this.setData({
      selectedSubject: '',
      selectedType: '',
      selectedDifficulty: '',
      currentPage: 1
    });
    this.loadQuestionData();
    this.closeFilter();
  },

  // 确认筛选
  confirmFilter: function() {
    this.setData({
      currentPage: 1
    });
    this.loadQuestionData();
    this.closeFilter();
  },

  // 加载试题数据
  async loadQuestionData() {
    if (this.data.isLoading) return;
    
    this.setData({
      isLoading: true
    });

    try {
      const params = {
        page: this.data.currentPage,
        pageSize: this.data.pageSize,
        keyword: this.data.searchKeyword
      };

      if (this.data.selectedSubject) {
        params.subject = this.data.selectedSubject;
      }

      if (this.data.selectedType) {
        params.type = this.data.selectedType;
      }

      if (this.data.selectedDifficulty) {
        params.difficulty = this.data.selectedDifficulty;
      }

      const result = await questionService.getQuestionList(params);
      
      if (result.success) {
        const questionList = this.data.currentPage === 1 ? result.data.list : [...this.data.questionList, ...result.data.list];
        
        this.setData({
          questionList,
          totalCount: result.data.total
        });
      } else {
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载试题失败', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        isLoading: false
      });
    }
  },

  // 加载更多试题
  loadMoreQuestions: function() {
    if (this.data.isLoading) return;
    if (this.data.questionList.length >= this.data.totalCount) return;
    
    this.setData({
      currentPage: this.data.currentPage + 1
    });
    
    this.loadQuestionData();
  },

  // 添加新试题
  addNewQuestion: function() {
    wx.navigateTo({
      url: '/pages/teacher/question/edit/edit',
    });
  },

  // 编辑试题
  editQuestion: function(e) {
    const questionId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/teacher/question/edit/edit?id=${questionId}`,
    });
  },

  // 删除试题
  deleteQuestion: function(e) {
    const questionId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这道试题吗？删除后无法恢复',
      confirmColor: '#f44336',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({
              title: '删除中...'
            });

            const result = await questionService.deleteQuestion(questionId);
            
            if (result.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              // 重新加载数据
              this.setData({
                currentPage: 1
              });
              this.loadQuestionData();
            } else {
              wx.showToast({
                title: result.message || '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('删除试题失败', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  // 导入试题
  importQuestions: function() {
    wx.navigateTo({
      url: '/pages/teacher/question/import/import',
    });
  },

  // 预览试题
  previewQuestion: function(e) {
    const questionId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/teacher/question/preview/preview?id=${questionId}`
    });
  }
}) 